package com.example.controller;

import com.example.entity.User;
import com.example.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * create by: Jipson Liang
 * on: 2020/11/1 20:32
 * desc:
 */
@RestController
public class UserController {
    @Autowired
    private UserRepository userRepository;

    /**
     * 增加User
     * @param name
     * @param email
     * @return
     */
    // localhost:8080/add?name=张三&email=zs@qq.com
    @RequestMapping("/add")
    public String addUser(@RequestParam String name, @RequestParam String email){

        User user1 = new User();
        user1.setName(name);
        user1.setEmail(email);
        //保存到数据库
        userRepository.save(user1);

        return "Saved";
    }

    /**
     * 更新
     * @param user
     * @return
     */
    @RequestMapping("/upd")
    public String updUser(User user){
        userRepository.save(user);
        return "Saved";
    }

    /**
     * 查询所有User
     * @return
     */
    @RequestMapping("/getAll")
    public Iterable<User> getAllUser(){
        Iterable<User> all = userRepository.findAll();
        return all;
    }

    /**
     * 按id删除
     * @param id
     * @return
     */
    // localhost:8080/del/2
    @RequestMapping("/del/{id}")
    public String delUserById(@PathVariable Integer id){
        userRepository.deleteById(id);
        return "Deleted";
    }


}
